package com.snailct.bpp.router.datachange;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by huangxa on 2016/5/22.
 */
public class XMLFileOperation {
    private String xmlFileName;
    private String messageRootElementName;
    private String parentElementName;
    private String currentElementName;
    private String parentPareElementName;
    private boolean bottoms;
    private String messageDirection;

    public void genInXMLFileAndRoot(){
        Element root = new Element("messageNodes");
        Document doc = new Document(root);
        Element messageRootElement = new Element("rootElementName");
        messageRootElement.addContent(messageRootElementName);
        root.addContent(messageRootElement);
        String filePath = new FilePath().getInFilePath(messageDirection);
        filePath += xmlFileName;
        writeFile(doc,filePath);
        XmlMessageConfig xmlMessageConfig = new XmlMessageConfig();
        xmlMessageConfig.setXmlFileName(xmlFileName);
        xmlMessageConfig.updateFileToTable();
    }
    public void genElement(){
        SAXBuilder builder = new SAXBuilder();
        String filePath = new FilePath().getInFilePath(messageDirection);
        filePath += xmlFileName;
        Document doc;
        try{
            doc = builder.build(filePath);
            Element root = doc.getRootElement();
            Element node = new Element("messageNode");
            root.addContent(node);
            Element parentElement = new Element("parentElementName");
            parentElement.setText(parentElementName);
            node.addContent(parentElement);
            Element currentElement = new Element("currentElementName");
            currentElement.setText(currentElementName);
            node.addContent(currentElement);
            Element isBottom = new Element("isBottom");
            isBottom.setText("false");
            node.addContent(isBottom);
            if(this.bottoms){
                isBottom.setText("true");
            }
            Element parentElementPrimaryKey = new Element("parentElementPrimaryKey");
            node.addContent(parentElementPrimaryKey);
            Element currentElementPrimaryKey = new Element("currentElementPrimaryKey");
            node.addContent(currentElementPrimaryKey);
            Element currentElementLevel = new Element("currentElementLevel");
            node.addContent(currentElementLevel);
            Element currentElementValue = new Element("currentElementValue");
            node.addContent(currentElementValue);
            Element tableName = new Element("tableName");
            node.addContent(tableName);
            Element fieldName = new Element("fieldName");
            node.addContent(fieldName);
            int level = Util.getElementLevel(doc,node);
            currentElementLevel.setText(new Integer(level).toString());
            tableName.setText(currentElementName);
            if(this.bottoms){
                tableName.setText(parentElementName);
                fieldName.setText(currentElementName);
            }
            writeFile(doc,filePath);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private void writeFile(Document doc,String filePath){
        try{
            File file = new File(filePath);
            if(!file.exists()){
                FileOperation.createFile(filePath);
            }
            FileWriter writer = new FileWriter(file);
            Format format = Format.getPrettyFormat();
            format.setEncoding("gb2312");
            XMLOutputter xmlOutputter = new XMLOutputter(format);
            xmlOutputter.output(doc,writer);
            writer.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    public void forKey(){
        SAXBuilder builder = new SAXBuilder();
        String filePath = new FilePath().getInFilePath(messageDirection);
        filePath += xmlFileName;
        Document doc;
        try{
            doc = builder.build(filePath);
            Element root = doc.getRootElement();
            List<?> nodeList = root.getChildren("messageNode");
            for(int i=0;i<nodeList.size();i++){
                Element tempElement = (Element)nodeList.get(i);
                if("false".equals(tempElement.getChildText("isBottom"))&&tempElement.getChildText("currentElementName").equals(parentElementName)){
                    tempElement.getChild("currentElementPrimaryKey").setText(currentElementName);
                    writeFile(doc,filePath);
                }
            }
        }catch (JDOMException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    public void finishSonNode(){
        ArrayList<MessageNode> sonArray = genAllSonElement();
        ArrayList<String> sonStrArray = new ArrayList<String>();
        for(int i=0;i<sonArray.size();i++){
            MessageNode node = sonArray.get(i);
            sonStrArray.add(node.getCurrentElementName());
        }
        String preXmlFileName = xmlFileName.substring(0,xmlFileName.lastIndexOf("."));
        MessageNode currentNode = currentElement();
        int level = Integer.parseInt(currentNode.getCurrentElementLevel());
        if(level>1){
            String priFieldName = parentElement(currentNode).getCurrentElementPrimaryKey();
            if(priFieldName!=null&&priFieldName.length()!=0){
                sonStrArray.add(priFieldName);
            }
        }
        Util.createTable(preXmlFileName+"_"+getCurrentElementName(),sonStrArray);
    }
    public MessageNode parentElement(MessageNode sonElement){
        ArrayList<MessageNode> pArray = genAllElement();
        for(int i=0;i<pArray.size();i++){
            MessageNode temp = pArray.get(i);
            int pi = Integer.parseInt(temp.getCurrentElementLevel());
            int si = Integer.parseInt(sonElement.getCurrentElementLevel());
            if((pi==si-1)&&sonElement.getParentElementName().equals(temp.getCurrentElementName())){
                return temp;
            }
        }
        return null;
    }
    public MessageNode currentElement(){
        SAXBuilder builder = new SAXBuilder();
        String filePath = new FilePath().getInFilePath(messageDirection);
        filePath += xmlFileName;
        Document doc;
        try{
            doc = builder.build(filePath);
            Element root = doc.getRootElement();
            List<?> nodeList = root.getChildren("messageNode");
            for(int i=0;i<nodeList.size();i++){
                Element tempElement = (Element)nodeList.get(i);
                if(tempElement.getChildText("currentElementName").equals(currentElementName)&&tempElement.getChildText("parentElementName").equals(parentElementName)){
                    MessageNode node = new MessageNode();
                    Util.formElementToMessageNode(tempElement,node);
                    return node;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    public List<MessageNode> getAllElement(){
        List<MessageNode> rtnArray = new ArrayList<MessageNode>();
        SAXBuilder builder = new SAXBuilder();
        String filePath = new FilePath().getInFilePath(messageDirection);
        filePath += xmlFileName;
        Document doc = null;
        try{
            doc = builder.build(filePath);
            Element root = doc.getRootElement();
            List<?> nodeList = root.getChildren("messageNode");
            for(int i=0;i<nodeList.size();i++){
                Element tempElement = (Element)nodeList.get(i);
                if("false".equals(tempElement.getChildText("isBottom"))){
                    MessageNode node = new MessageNode();
                    Util.formElementToMessageNode(tempElement,node);
                    rtnArray.add(node);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return rtnArray;
    }
    public List<MessageNode> getAllElement4Web(){
        List<MessageNode> rtnArray = new ArrayList<MessageNode>();
        SAXBuilder builder = new SAXBuilder();
        String filePath = new FilePath().getInFilePath(messageDirection);
        filePath += xmlFileName;
        Document doc = null;
        try{
            doc = builder.build(filePath);
            Element root = doc.getRootElement();
            List<?> nodeList = root.getChildren("messageNode");
            for(int i=0;i<nodeList.size();i++){
                Element tempElement = (Element)nodeList.get(i);

                    MessageNode node = new MessageNode();
                    Util.formElementToMessageNode(tempElement,node);
                    rtnArray.add(node);

            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return rtnArray;
    }
    public ArrayList<MessageNode> genAllElement(){
        ArrayList<MessageNode> returnArray = new ArrayList<MessageNode>();
        SAXBuilder builder = new SAXBuilder();
        String filePath = new FilePath().getInFilePath(messageDirection);
        filePath += xmlFileName;
        Document doc;
        try{
            doc = builder.build(filePath);
            Element root = doc.getRootElement();
            List<?> nodeList = root.getChildren("messageNode");
            for(int i=0;i<nodeList.size();i++){
                Element tempElement = (Element)nodeList.get(i);
                if("false".equals(tempElement.getChildText("isBottom"))){
                    MessageNode node = new MessageNode();
                    Util.formElementToMessageNode(tempElement,node);
                    returnArray.add(node);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return returnArray;
    }
    public ArrayList<MessageNode> genAllSonElement(){
        ArrayList<MessageNode> returnArray = new ArrayList<MessageNode>();
        SAXBuilder builder = new SAXBuilder();
        String filePath = new FilePath().getInFilePath(messageDirection);
        filePath += xmlFileName;
        Document doc;
        try{
            doc = builder.build(filePath);
            Element root = doc.getRootElement();
            List<?> nodeList = root.getChildren("messageNode");
            for(int i=0;i<nodeList.size();i++){
                Element tempElement = (Element)nodeList.get(i);
                if("true".equals(tempElement.getChildText("isBottom"))&&tempElement.getChildText("parentElementName").equals(currentElementName)){
                    MessageNode node = new MessageNode();
                    Util.formElementToMessageNode(tempElement,node);
                    returnArray.add(node);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return returnArray;
    }
    public String getXmlFileName() {
        return xmlFileName;
    }

    public void setXmlFileName(String xmlFileName) {
        this.xmlFileName = xmlFileName;
    }

    public String getMessageRootElementName() {
        return messageRootElementName;
    }

    public void setMessageRootElementName(String messageRootElementName) {
        this.messageRootElementName = messageRootElementName;
    }

    public String getParentElementName() {
        return parentElementName;
    }

    public void setParentElementName(String parentElementName) {
        this.parentElementName = parentElementName;
    }

    public String getCurrentElementName() {
        return currentElementName;
    }

    public void setCurrentElementName(String currentElementName) {
        this.currentElementName = currentElementName;
    }

    public boolean isBottoms() {
        return bottoms;
    }

    public void setBottoms(boolean bottoms) {
        this.bottoms = bottoms;
    }

    public String getMessageDirection() {
        return messageDirection;
    }

    public void setMessageDirection(String messageDirection) {
        this.messageDirection = messageDirection;
    }

    public String getParentPareElementName() {
        return parentPareElementName;
    }

    public void setParentPareElementName(String parentPareElementName) {
        this.parentPareElementName = parentPareElementName;
    }
}
